package com.help10000.rms.mvp.presenter

import com.amir.common.api.ApiContents
import com.amir.common.api.CustomObserver
import com.amir.common.api.upload.FileUploadObserver
import com.amir.common.beans.BaseResult
import com.amir.common.beans.FileEntity
import com.amir.common.beans.LogOffResult
import com.amir.common.beans.UserHomeInfoWrapper
import com.amir.common.beans.UserInfoEntity
import com.amir.common.mvp.model.Model
import com.amir.common.utils.Constant
import com.amir.common.utils.LogUtils
import com.amir.common.utils.SPUtils
import com.amir.common.utils.Utils
import com.help10000.kottlinbaselib.api.upload.UploadFileRequestBody
import com.help10000.rms.config.globalData
import com.help10000.rms.mvp.view.UserInfoView
import com.help10000.rms.ui.utils.ImageCompressor
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.MultipartBody
import okhttp3.ResponseBody
import java.io.File
import java.net.URLEncoder
import java.util.Observer

open class UserInfoPresenter(view: UserInfoView) : RefreshTokenPresenter(view) {

    fun logOff() {
        // 关键修正：先调用单参数方法，再用 ?: 处理 null，确保返回非空 String
        val accessToken = SPUtils.getString(Constant.AccessToken) ?: ""
        // 解释：如果 SP 中没有该 key，getString 返回 null，此时用 "" 代替，转为非空 String

        LogUtils.I("UserInfoPresenter", "开始注销账号，AccessToken: $accessToken")

        // 调用 API 时，accessToken 已是非空 String，解决类型不匹配
        val logOffApi = Model.getServer().logOff(accessToken)

        Model.getObservable(logOffApi, object : CustomObserver<LogOffResult>(mvpView) {
            override fun success(t: LogOffResult) {
                LogUtils.I("UserInfoPresenter", "注销成功，返回数据: $t")
                mvpView?.onLogOffSuccess(t)
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                LogUtils.E("UserInfoPresenter", "注销失败: ${e.message ?: "未知错误"}")
                mvpView?.dismissLoading()
            }
        })
    }


    fun getAboutUrl(): String {
        var AccessToken = SPUtils.getString(Constant.AccessToken)
        return ApiContents.webBaseUrl + ApiContents.About + "?AccessToken=${AccessToken}"
    }

    fun initUserInfo() {
        var AccessToken = SPUtils.getString(Constant.AccessToken)
        val templateCode = SPUtils.getString(Constant.TemplateCode)
        val appId = SPUtils.getString(Constant.APPId)
        if (AccessToken != null) {
            val token = Model.getServer().initUserInfo(AccessToken, appId, templateCode)
            Model.getObservable(token, object : CustomObserver<UserHomeInfoWrapper>(mvpView) {

                override fun success(t: UserHomeInfoWrapper) {
                    globalData.userInfo = t.data.UserInfo
                    mvpView?.userInfoSucc(t.data)
                }
            })
        }

    }

    @Deprecated("获取用户信息暂时不用")
    fun getUserInfo() {
        val accountid = SPUtils.getString(Constant.accountid)
        val access_token = SPUtils.getString(Constant.AccessToken)
        if (accountid != null) {
            val userInfo = Model.getServer().getUserInfo(access_token!!, accountid, "zh_CN")
            Model.getObservable(userInfo, object : CustomObserver<UserInfoEntity>(mvpView) {

                override fun success(t: UserInfoEntity) {
                    t.save()
                    // mvpView?.userInfoSucc(t)
                }
            })
        }
    }

    fun loginOut() {
        val accessToken = SPUtils.getString(Constant.AccessToken)
        if (accessToken != null) {
            val userInfo = Model.getServer().loginOut(accessToken)
            Model.getObservable(userInfo, object : CustomObserver<BaseResult>(mvpView) {

                override fun success(t: BaseResult) {
                    SPUtils.remove(Constant.AccessToken)
                    mvpView?.loginOutSuccess(t)
                    globalData.token = null
                    globalData.userInfo = null
                }
            })
        }
    }


    fun updateAvatar(url: String) {
        val accessToken = SPUtils.getString(Constant.AccessToken)
        if (accessToken != null) {
            val userInfo = Model.getServer().updateAvatar(accessToken, url)
            Model.getObservable(userInfo, object : CustomObserver<BaseResult>(mvpView) {

                override fun success(t: BaseResult) {
                    mvpView?.onAvatarUpdateSuccess()
                }
            })
        }
    }

    fun upFile(file: File) {
        val accessToken = SPUtils.getString(Constant.AccessToken)

        ImageCompressor.compressAsync(context = Utils.getContext(), sourceFile = file)
            .onErrorReturn { file } // 压缩失败就上传原图
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ compressedFile ->
                val requestBody = UploadFileRequestBody(compressedFile, mFileUploadObserver)
                val part = MultipartBody.Part.createFormData("file",
                    URLEncoder.encode(compressedFile.name,"utf-8"),
                    requestBody)
                val upAvatar = Model.getServer().UploadFile(accessToken, part)

                Model.getObservable(upAvatar, object : CustomObserver<FileEntity>(mvpView) {
                    override fun success(t: FileEntity) {
                        mvpView?.onAvatarUpload(t.FileName)
                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        mvpView?.dismissLoading()
                    }
                })
            }, { error ->
                LogUtils.I("UserInfoPresenter","图片压缩失败: ${error.message}")
                mvpView?.dismissLoading()
            })
    }

    private val mFileUploadObserver = object : FileUploadObserver<ResponseBody>(mvpView) {
        override fun onUpLoadSuccess(t: ResponseBody) {

        }

        override fun onUpLoadFail(e: Throwable) {

        }

        override fun onProgress(progress: Int) {

        }
    }

    override fun getMvpView(): UserInfoView {
        return super.getMvpView() as UserInfoView
    }
}